package ch.zbw.pra.sysventory.dataaccess.dataAccessObject;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import org.joda.time.LocalDate;
import org.springframework.context.ApplicationContext;

import ch.zbw.pra.sysventory.database.jdbcTemplate.ScanversionJDBCTemplate;
import ch.zbw.pra.sysventory.model.Computer;
import ch.zbw.pra.sysventory.model.Scanversion;
import ch.zbw.pra.sysventory.utils.DatabaseUtils;

/**
 * Bereitet Daten für den Zugriff auf die Datenbank im DatabaseLayer auf
 * 
 * @author Ralph Koster & Roberto Lucas
 */

public class ScanversionDataAccessObject implements Serializable {

	private static final long serialVersionUID = 6813658176571958495L;
	
	private ApplicationContext context;
	private ScanversionJDBCTemplate scanversionJDBCTemplate;
	private ComputerDataAccessObject computerDataAccessObject;
	
	public ScanversionDataAccessObject() {
		context = DatabaseUtils.getContext();
		scanversionJDBCTemplate = (ScanversionJDBCTemplate)context.getBean("scanversion");
		
		this.computerDataAccessObject = new ComputerDataAccessObject();
	}
	
	public List<Scanversion> getAllScanversionsFromDataaccess() {
		List<Scanversion> scanversions = getAllScanversionsFromDatabase();
		for(Scanversion scanversion : scanversions) {
			Integer scanversionId = scanversion.getId();
			scanversion.setComputers(computerDataAccessObject.getComputersFromScanversion(scanversionId));
		}
		return scanversions;
	}	

	public void saveScanversion(Scanversion scanversion) {
		Integer scanversionId = writeScanversionToDatabase(scanversion);
		List<Computer> computers = scanversion.getComputers();
		if(null != computers && computers.size() != 0) {
			for(Computer computer : computers) {
				computerDataAccessObject.saveComputer(computer, scanversionId);
			}
		}
	}
	
	public Integer writeScanversionToDatabase(Scanversion scanversion) {
		Integer scanversionId = scanversionJDBCTemplate.insertScanversion(scanversion);
		return scanversionId;
	}

	public Scanversion getLastScanversion() {
		Scanversion scanversion = scanversionJDBCTemplate.getLastScanversion();
		return scanversion;
	}

	public Integer getNumberOfScansInTimerange(
			HashMap<String, LocalDate> timerange) {
		Integer numberOfScans = scanversionJDBCTemplate.getNumberOfScansInTimerange(timerange);
		return numberOfScans;
	}

	public List<Scanversion> getAllScanversionsFromDatabase() {
		List<Scanversion> scanversions = scanversionJDBCTemplate.getAllScanversions();
		return scanversions;
	}
}
